<script lang="ts" setup>
import { Message, Modal } from '@arco-design/web-vue';
import { useStore } from '@renderer/Store';
import { ref, watch } from 'vue';


interface FileInfo{
  fileName: string;
  fileFullPath: string;
}


const fileNames = ref<FileInfo[]>( [] );
const currentFilePath = ref<string>( '' );

const store = useStore();

// 更清晰的初始化逻辑
const initialize = () => resetDirectory( true );
onMounted( initialize );

// 使用async/await重构
const resetDirectory = async ( isDefaultDirectory: boolean ) => {
  try{
    const files = await window.api.fetchDirectory( isDefaultDirectory );
    
    if( files.length > 0 ){
      fileNames.value = files;
      currentFilePath.value = files[ 0 ].fileFullPath;
    }
    else{
      fileNames.value = [];
      currentFilePath.value = '';
      Message.error( {
        content: '当前目录无码表',
        duration: 3000
      } );
    }
  }
  catch( err ){
    Message.error( {
      content: `读取目录失败：${ err }`,
      duration: 3000
    } );
  }
};

// 完善路径变更处理
watch( currentFilePath, async ( newPath, oldPath ) => {
  try{
    const { codeTable } = store;
    if( !codeTable?.value ){
      await store.fetchDict( newPath );
      return;
    }
    
    if( newPath === codeTable.value.data.filePath ){
      return;
    }
    
    if( codeTable.value.changedRowLength > 0 ){
      await handleUnsavedChanges();
    }
    
    await store.fetchDict( newPath );
  }
  catch( error ){
    // 恢复原路径并提示
    currentFilePath.value = oldPath;
    if( error instanceof Error && error.message === '用户点击取消' ){
      Message.info( {
        content: '操作已取消',
        duration: 1000
      } );
    }
    else{
      Message.error( {
        content: '操作异常',
        duration: 2000
      } );
    }
  }
} );

// 增强弹窗交互处理
const handleUnsavedChanges = () => {
  return new Promise<void>( ( resolve, reject ) => {
    Modal.confirm( {
      title: '警告',
      content: '有未保存的修改，是否保存？',
      okButtonProps: { status: 'danger' },
      onOk: async () => {
        try{
          await store.codeTable.value?.update();
          Message.success( {
            content: `保存成功，路径：${ store.codeTable.value?.data.filePath }`,
            duration: 3000
          } );
          resolve();
        }
        catch( error ){
          Message.error( {
            content: '保存失败',
            duration: 3000
          } );
          reject( new Error( '保存失败' ) );
        }
      },
      onCancel: () => reject( new Error( '用户点击取消' ) )
    } );
  } );
};
</script>

<template>
  <div class="panel block">
    <div class="mb-4">
      <a-button type="primary" @click="resetDirectory(false)">码表目录</a-button>
      <a-button type="primary" @click="resetDirectory(true)">重置默认</a-button>
    </div>
    <a-radio-group v-model="currentFilePath" class="vertical" type="button">
      <a-radio v-for="file in fileNames" :key="file.fileFullPath" :value="file.fileFullPath">
        {{ file.fileName }}
      </a-radio>
    </a-radio-group>
  </div>
</template>
